import time
import os

from selenium import webdriver
import requests

class BlackBird():
    browser = None
    login_url = None
    def __init__(self, login_url):
        self.login_url = login_url

    def _browser_initial(self):
        self.browser = webdriver.Chrome(executable_path="./chromedriver.exe")
        self.browser.implicitly_wait(4)
        self.browser.get(login_url)

    def get_cookies(self):
        self._browser_initial()
        self.browser.find_elements_by_class_name("padding0")[0].click()
        time.sleep(10) #  等待扫码

        self.browser.get("https://www.blackbirdsport.com/user/records/upload")
        c = self.browser.get_cookies()
        cookies = {}
        # 获取cookie中的name和value,转化成requests可以使用的形式
        for cookie in c:
            cookies[cookie['name']] = cookie['value']
        return cookies

    def _get_fits_path(self):
        """
        获取 fit 文件夹中的 fit 文件
        :return:
        """
        fits = os.listdir("./fit")
        fit_cwd = os.getcwd() + "\\fit\\"
        """        
                fits_path = []
                for fit in fits:
                    # print(fit_cwd + fit)
                    fits_path.append(fit_cwd + fit)
        """
        path_list = [os.path.join( fit_cwd, x) for x in fits]
        path_split_by_newline = '\n'.join(path_list)

        return path_split_by_newline

    def upload_fits(self):
        """
        批量上传
        :return:
        """
        cookies = self.get_cookies()
        paths =  self._get_fits_path()

        upload = self.browser.find_elements_by_class_name("form-control-file")[0]
        upload.send_keys(paths)
        print ("value: " +upload.get_attribute('value'))

if __name__ == '__main__':
    global browser
    login_url = "https://www.blackbirdsport.com/auth/login"
    black_bird = BlackBird(login_url)
    black_bird.upload_fits()
    # cookies = black_bird.get_cookies()


    # 测试 cookies

    # response = requests.get("https://www.blackbirdsport.com/api/records?lastRecordId=0&pageSize=25", cookies=cookies)
    # print(response.text)
    # print(cookies)